<template>
  <div class="layout-container antijam-test-sample-data">
    <div class="search common-buttons">
      <el-input
        v-model="keyword"
        style="width: 320px"
        placeholder="请搜索"
        clearable
      ></el-input>
      <el-button type="primary" :icon="Search" @click="onQuery({ pageNo: 1 })"
        >查找</el-button
      >
    </div>
    <div class="layout-container-table">
      <CommonTable
        :data="state.tableData"
        v-model:page="page"
        :total="total"
        v-loading="loading"
        :showSelection="false"
        highlight-current-row
        @onQuery="onQuery"
        @current-change="handleCurrentChange"
        :header-cell-style="{ 'text-align': 'center' }"
        :cell-style="{ 'text-align': 'center' }"
        style="width: 100%"
      >
        <el-table-column prop="caseName" label="对抗案例名称" />
        <el-table-column prop="updateTime" label="更新时间" />
        <el-table-column prop="studen" label="边界推算状态" width="100">
          <template #default="scope">
            <div
              class="evaluation-process"
              v-if="scope.row.boundaryFlag === '0'"
            >
              <div class="round" style="background: #3868fe"></div>
              <span style="color:#3868fe">未完成推算</span>
            </div>
            <div
              class="evaluation-process"
              v-if="scope.row.boundaryFlag === '1'"
            >
              <div class="round" style="background: rgba(22, 168, 49, 1)"></div>
              <span style="color:rgba(22, 168, 49, 1)">完成推算</span>
            </div>
          </template>
        </el-table-column>
                <el-table-column label="案例查看">
          <template #default="scope">
            <el-button link size="small" @click="checkCite(scope.row.sampleIds)" text
              >查看</el-button
            >
          </template>
        </el-table-column>
        <el-table-column label="边界推算结果">
          <template #default="scope">
            <!-- update——resultUrl -->
            <span v-if="scope.row.boundaryFlag == 0">
              <span>未推算</span>
            </span>
            <span v-else>
              <el-button
                link
                size="small"
                @click="calculate(scope.row.caseName, scope.row.id, scope.row)"
                text
                >查看</el-button>
            </span>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button link size="small" @click="onDelete(scope.row.id)" text
              >删除</el-button
            >
          </template>
        </el-table-column>
      </CommonTable>
    </div>
    <div class="step-buttons common-buttons">
      <el-button type="primary" @click="createdialog">创建案例</el-button>
      <el-button type="primary" @click="onStep">开始推算</el-button>
    </div>
    <!-- 查看包含样本 -->
    <el-dialog
      v-model="dialogcheckCiteVisible"
      title="案例信息"
      width="750px"
    >
      <div>
        <CommonTable
          :data="statecheckCite.tableData"
          v-model:page="checkCitepage"
          :total="checkCitetotal"
          v-loading="Citecheckloading"
          height="300px"
          @onQuery="oncheckQuery"
          :show-selection="false"
          :show-pagination="false"
          :header-cell-style="{ 'text-align': 'center' }"
          :cell-style="{ 'text-align': 'center' }"
          style="width: 100%"
        >
          <el-table-column prop="sampleName" label="试验样本名称" />
          <el-table-column prop="scenarioDes" label="作战想定场景" />
          <el-table-column prop="dytStyle" label="导引头体制" />
          <el-table-column prop="interType" label="干扰类型" />

        </CommonTable>
      </div>
      <template #footer>
        <div class="step-buttons common-buttons">
          <el-button type="primary" @click="formcheckReset(Citeformref)"
            >确认</el-button
          >
        </div>
      </template>
    </el-dialog>
    <!-- 添加 -->
    <el-dialog
      v-model="dialogAddCiteVisible"
      title="创建对抗案例"
      width="750px"
    >
      <div>
        <el-form
          :model="Citeform"
          ref="Citeformref"
          :inline="true"
          :rules="QueryCiterules"
        >
          <el-form-item label="对抗案例名称" prop="caseName">
            <el-input
              v-model="Citeform.caseName"
              autocomplete="off"
              type="textarea"
              placeholder="请输入"
              style="width: 400px"
            />
          </el-form-item>
          <TagIcon title="选择试验样本" />
          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item
                label="作战想定场景"
                :label-width="formLabelWidth"
                prop="scenarioDes"
              >
                <el-select
                  v-model="Citeform.scenarioDes"
                  placeholder="请选择"
                  @change="onQueryCite({ pageNo: 1 })"
                >
                  <el-option label="---" value="" />
                  <el-option label="作战区域" value="作战区域" />
                  <el-option label="作战时间" value="作战时间" />
                  <el-option label="作战任务" value="作战任务" />
                  <el-option label="敌我实战装备部署情况" value="敌我实战装备部署情况" />
                </el-select>
              </el-form-item>
              <el-form-item
                label="导引头体制"
                :label-width="formLabelWidth"
                prop="dytStyle"
              >
                <el-select
                  v-model="Citeform.dytStyle"
                  placeholder="请选择"
                  @change="onQueryCite({ pageNo: 1 })"
                >
                  <el-option label="---" value="" />
                  <el-option label="雷达(被动)" value="雷达(被动)" />
                  <el-option label="雷达(主动)" value="雷达(主动)" />
                  <el-option label="红外" value="雷达(主动)" />
                  <el-option label="雷达-红外复合制导" value="雷达(主动)" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                label="干扰类型"
                :label-width="formLabelWidth"
                prop="interType"
              >
                <el-select
                  v-model="Citeform.interType"
                  placeholder="请选择"
                  @change="onQueryCite({ pageNo: 1 })"
                >
                  <el-option label="---" value="" />
                  <el-option
                    label="舰载有源干扰-雷达"
                    value="舰载有源干扰-雷达"
                  />
                  <el-option
                    label="舷外有源干扰-雷达"
                    value="舷外有源干扰-雷达"
                  />
                  <el-option label="角反干扰-雷达" value="角反干扰" />
                  <el-option label="箔条干扰-雷达" value="箔条干扰" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div class="layout-container-table">
          <CommonTable
            :data="stateAddCite.tableData"
            v-model:page="Citepage"
            :total="Citetotal"
            v-loading="Citeloading"
            :show-pagination="false"
            height="200px"
            @onQuery="onQueryCite"
            @selection-change="onSelectChange"
            :header-cell-style="{ 'text-align': 'center' }"
            :cell-style="{ 'text-align': 'center' }"
            style="width: 100%"
          >
          <el-table-column prop="sampleName" label="试验样本名称" />
          <el-table-column prop="scenarioDes" label="作战想定场景" />
          <el-table-column prop="dytStyle" label="导引头体制" />
          <el-table-column prop="interType" label="干扰类型" />
          </CommonTable>
        </div>
      </div>
      <template #footer>
        <div class="step-buttons common-buttons">
          <el-button
            type="primary"
            @click="
              dialogAddCiteVisible = false;
              formReset(Citeformref);
            "
            >取消</el-button
          >
          <el-button type="primary" @click="createCite(Citeformref)"
            >确认</el-button
          >
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue';
import { ElMessage, FormInstance, ElMessageBox } from 'element-plus';
import { useRoute, useRouter } from 'vue-router';
import { Search } from '@element-plus/icons-vue';
import CommonTable from '@/components/common-table/index.vue';
import { Page } from '@/components/common-table/type';
import TagIcon from '@/components/tag-icon/index.vue'
import {
  CiteList,
  addCiteList,
  addCite,
  delCase
} from '@/api/antiJamPerformBoundaryCalculate';

let $router = useRouter();
const keyword = ref<string>('');
const state = reactive<any>({
  tableData: [],
});
const selectKeys = ref<string[]>([]);
const loading = ref<boolean>(false);
const page = reactive<Page>({
  current: 1,
  pageSize: 20,
});
const total = ref<number>(0);
// 当前行
const currentRow = ref({});
const options = Array.from({ length: 1000 }).map((_, idx) => ({
  value: `${idx + 1}`,
  label: `${idx + 1}`,
}));
//查看弹出框
const Citecheckloading = ref<boolean>(false);
const dialogcheckCiteVisible = ref(false);
const statecheckCite = reactive<any>({
  tableData: [],
});
const checkCitepage = reactive<Page>({
  current: 1,
  pageSize: 20,
});
const checkCitetotal = ref<number>(0);
const checkCite = async (ids: any) => {
  dialogcheckCiteVisible.value = true;
  oncheckQuery({ sampleId: ids });
};
const oncheckQuery = async (val: any) => {
  const params = {
    pageSize: 1000,
    pageNo: 1,
    ...val,
  };
  Citecheckloading.value = true;
  let result = await addCiteList(params);
  Citecheckloading.value = false;
  const { rows, totalRows } = result.data;
  checkCitetotal.value = totalRows;
  statecheckCite.tableData = rows;
  currentRow.value = {};
};
const formcheckReset = (forml: FormInstance) => {
  formReset(forml);
  dialogcheckCiteVisible.value = false;
  statecheckCite.tableData = [];
  onQuery({ pageNo: 1 });
};

//创建弹出框
const Citeloading = ref<boolean>(false);
const dialogAddCiteVisible = ref(false);
const formLabelWidth = '100px';
const stateAddCite = reactive<any>({
  tableData: [],
});
const Citeform = ref<any>({});
const Citeformref = ref<FormInstance>();
const Citepage = reactive<Page>({
  current: 1,
  pageSize: 20,
});
const Citetotal = ref<number>(0);
onMounted(() => {
  onQuery({ pageNo: 1 });
});
// 查询数据 查询处理后是否
const onQuery = async (val: any) => {
  const params = {
    caseName: keyword.value,
    pageSize: page.pageSize,
    pageNo: page.current,
    ...val,
  };
  loading.value = true;
  let result = await CiteList(params);
  loading.value = false;
  const { rows, totalRows } = result.data;
  total.value = totalRows;
  state.tableData = rows;
  currentRow.value = {};
};
//提交验证
const submitForm = (formEl: FormInstance) => {
  let x = formEl.validate((valid: any) => {});
  return x;
};
//表单重置
const formReset = (formEl: FormInstance) => {
  if (!formEl) return;
  formEl.resetFields();
  onQuery({ pageNo: 1 });
  stateAddCite.tableData = [];
};
const QueryCiterules = {
  caseName: [{ required: true, message: '请输入', trigger: 'change' }],
};
const createdialog = async () => {
  dialogAddCiteVisible.value = true;
  onQueryCite({ pageNo: 1 });
};

const createCite = async (formEl: FormInstance) => {
  let x = await submitForm(formEl);
  if (!x) {
    return;
  }
  if (selectKeys.value.length < 1) {
    ElMessage({
      message: '请至少选择一条试验样本数据!',
      type: 'warning',
    });
    return;
  }
  let params = {
    sampleIds: toResverStr(selectKeys.value),
    ...Citeform.value,
  };
  let result = await addCite(params);
  ElMessage.success('创建成功');
  dialogAddCiteVisible.value = false;
  selectKeys.value = [];
  formReset(formEl);
};
// 查询表格数据
const onQueryCite = async (val: any) => {
  const params = {
    evaluationStage: '4',
    sampleId: '',
    pageSize: 1000,
    pageNo: 1,
    ...Citeform.value,
    ...val,
  };
  Citeloading.value = true;
  let result = await addCiteList(params);
  Citeloading.value = false;
  const { rows, totalRows } = result.data;
  Citetotal.value = totalRows;
  stateAddCite.tableData = rows;
};
// 过滤出keys
const filterKeys = (arr: []) => {
  let keys: string[] = [];
  for (let item of arr) {
    keys.push(item.id);
  }
  return keys;
};
// 选择监听器
const onSelectChange = (val: []) => {
  selectKeys.value = filterKeys(val);
};
const toResverStr = (data: string[]) => {
  const str = data.join(',');
  return str;
};
// 选中当前行
const handleCurrentChange = (val: Object | undefined) => {
  currentRow.value = val;
};
//删除
const onDelete = async(id:any) => {
  ElMessageBox.confirm(
    '确定要删除此案例信息吗?',
    '温馨提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async() => {
      let params = {
        caseIds:id
      }
      let result = await delCase(params);
      ElMessage({
        type: 'success',
        message: '删除成功',
      })
      onQuery({ pageNo: 1 });
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '用户取消删除',
      })
    })
}
const calculate = (name: any, id: any, row: any) => {
  let rowvalue = encode(JSON.stringify(row));
  $router.push({
    path: '/antiJamPerformBoundaryCalculate/boundaryCalculate',
    query: {
      dealSampleId: id,
      looknum: 1,
      value: rowvalue,
      dealSamplename: name,
    },
  });
};

//加密
const encode = (str: string) => {
  return btoa(
    encodeURIComponent(str).replace(
      /%([0-9A-F]{2})/g,
      function toSolidBytes(match, p1) {
        return String.fromCharCode('0x' + p1);
      }
    )
  );
};
//行
const onStep = () => {
  if (!currentRow.value.id) {
    ElMessage({
      message: '请选择一条案例数据!',
      type: 'warning',
    });
    return;
  }
  $router.push({
    path: '/antiJamPerformBoundaryCalculate/boundaryCalculate',
    query: {
      dealSampleId: currentRow?.value.id,
      looknum: 0,
      dealSamplename: currentRow?.value.caseName,
    },
  });
};
</script>

<style lang="scss" scoped>
@import '@/assets/style/buttons';
.antijam-test-sample-data {
  .search {
    display: flex;
    padding: 16px;
    :deep() {
      .el-input--small .el-input__wrapper {
        margin-right: 10px;
      }
    }
  }
  .layout-container-table {
    .el-button--small {
      background: transparent;
      color: rgba(24, 81, 237, 1);
      font-size: 13px;
    }
  }

  .evaluation-process {
    display: flex;
    cursor: pointer;
    // color: rgb(24, 81, 237);
    .round {
      display: inline-block;
      width: 10px;
      height: 10px;
      border-radius: 50%;
      position: relative;
      top: 7px;
      right: 4px;
    }
  }

  .step-buttons {
    display: flex;
    justify-content: center;
    box-shadow: 0px 0px 10px rgba(218, 222, 224, 1);
    padding: 10px 0;
  }
  :deep(.el-dialog__footer){
    padding: 0;
  }
  :deep(.el-dialog__body){
    padding: 10px 16px;
  }
  :deep(.el-select .el-input__wrapper){
    width: 160px;
  }

}
</style>
